<template>
  <div>
    <div class="mb-4.5">
      <span class="text-lg text-color-main font-semibold mr-3.5">点位默认属性</span>
      <span class="text-color-secondary">必填属性</span>
    </div>
    <div class="mb-7">
      <a-input :readonly="true" class="w-full" value="点位名称" />
    </div>
    <div class="mb-4.5">
      <span class="text-lg text-color-main font-semibold mr-3.5">点位扩展属性</span>
      <span class="text-color-secondary">可以自定义，并按需设置为必填或选填</span>
    </div>
    <a-form-item v-for="(el, i) in dyAttrs" :key="i" :validate-status="el.validateStatus">
      <div class="flex flex-row items-center">
        <div class="flex-1">
          <a-input
            v-model:value="el.datapointAttrName"
            class="w-full"
            placeholder="请输入属性名称"
            :maxlength="64"
            @change="el.validateStatus = 'success'"
          />
        </div>
        <div class="ml-7">
          <a-radio-group v-model:value="el.requires" :options="requiredOptions" />
        </div>
        <div>
          <a-button type="link" danger @click="removeAttr(i)">
            <template #icon>
              <Icon type="icon-shanchu" />
            </template>
            删除
          </a-button>
        </div>
      </div>
    </a-form-item>
    <a-button type="dashed" block :disabled="dyAttrs.length >= 30" @click="addAttr">
      <template #icon>
        <Icon type="icon-tianjia" />
      </template>
      添加扩展属性
    </a-button>
  </div>
</template>
<script setup lang="ts">
import { message } from "ant-design-vue";
import { ref } from "vue";
import type { GatewayTypeAttrItem } from "/@/api/aiot/gateway/models";
const dyAttrs = ref<Partial<GatewayTypeAttrItem>[]>([]);
const requiredOptions = ref([
  { label: "必填", value: true },
  { label: "选填", value: false },
]);
function addAttr() {
  dyAttrs.value.push({
    datapointAttrName: "",
    requires: true,
  });
}
function removeAttr(i) {
  dyAttrs.value.splice(i, 1);
}

defineExpose({
  getData(isValid) {
    if (isValid) {
      for (let i = 0; i < dyAttrs.value.length; i++) {
        const item = dyAttrs.value[i];
        if (!item.datapointAttrName) {
          item.validateStatus = "error";
          message.error("请输入属性名称");
          return null;
        }
        if (item.datapointAttrName.length > 64) {
          item.validateStatus = "error";
          message.error("属性名称不能超过64个字符");
          return null;
        }
      }
    }
    return dyAttrs.value;
  },
  clear() {
    dyAttrs.value = [];
  },
  setData(data) {
    dyAttrs.value = data;
  },
});
</script>
